package datastructure.sort;

import java.util.Arrays;

import static utils.Utils.shuffle;
import static utils.Utils.swap;

/**
 * @Author ZhangCuirong
 * @Date 2025/7/30 10:05
 * @description: 冒泡排序
 */
public class BubbleSort {
    public static void bubbleSort(int[] nums) {
        if (nums == null || nums.length <= 1) {
            return;
        }
        for (int i = 0; i < nums.length - 1; i++) {//冒牌n-1次数
            boolean swapped = false;
            //j代表冒泡的范围
            for (int j = 0; j < nums.length - i - 1; j++) {//冒泡出最大的放在末尾,如果不冒泡说明有序
                if (nums[j] > nums[j + 1]) {
                    swap(nums, j, j + 1);
                    swapped = true;
                }
            }
            if (!swapped) {
                break;
            }
        }
    }

    public static void main(String[] args) {
        int[] nums = {2, 3, 1, 4, 6, -1, -4, -10};
        shuffle(nums);
        System.out.println(Arrays.toString(nums));
        bubbleSort(nums);
        System.out.println(Arrays.toString(nums));
    }
}
